// LoginLogServiceImpl.java
package com.csxy.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.csxy.six.R;
import com.csxy.six.R2;
import com.csxy.six.entity.LoginLog;
import com.csxy.six.mapper.LoginLogMapper;
import com.csxy.six.service.LoginLogService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class LoginLogServiceImpl extends ServiceImpl<LoginLogMapper, LoginLog> implements LoginLogService {

    @Override
    public R2<Void> recordLogin(Long userId, String ip, String device, boolean success) {
        LoginLog log = new LoginLog();
        log.setUserId(userId);
        log.setIpAddress(ip);
        log.setDevice(device);
        log.setStatus(success ? 1 : 0);
        log.setCreateTime(LocalDateTime.now());
        this.save(log);
        return R2.ok();
    }

    @Override
    public R2<List<LoginLog>> getLoginHistory(Long userId) {
        QueryWrapper<LoginLog> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId)
                .orderByDesc("create_time");
        return R2.ok(this.list(wrapper));
    }

    @Override
    public R2<List<LoginLog>> getRecentFailedLogins(String ip) {
        QueryWrapper<LoginLog> wrapper = new QueryWrapper<>();
        wrapper.eq("ip_address", ip)
                .eq("status", 0)
                .ge("create_time", LocalDateTime.now().minusHours(1))
                .orderByDesc("create_time");
        return R2.ok(this.list(wrapper));
    }
}